/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.gui.mvc.utilities;

import org.testis.utils.tree.DefaultMutableLabelNode;
import java.util.HashMap;
import javax.swing.tree.DefaultTreeModel;

import org.testis.orm.classes.T_test_label;
import org.testis.utils.middleware.DefaultLabelTreeDataHandler;
import org.testis.utils.tree.LabelTreeNode;
import org.testis.utils.tree.TreeNode;

/**
 *
 * @author selcuk
 */
public class DefaultLabelTreeModelLoader implements ILabelTreeModelLoader {

    @Override
    public DefaultTreeModel loadTreeModel() {
        DefaultMutableLabelNode rootNode = loadLabelsTree(null);
        DefaultTreeModel model = new DefaultTreeModel(rootNode);
        return model;
    }

    @Override
    public DefaultTreeModel loadTreeModel(HashMap selectedLabels) {
        DefaultMutableLabelNode rootNode = loadLabelsTree(selectedLabels);
        DefaultTreeModel model = new DefaultTreeModel(rootNode);
        return model;
    }

    private DefaultMutableLabelNode loadLabelsTree(HashMap selectedLabels) {
        DefaultLabelTreeDataHandler handler = new DefaultLabelTreeDataHandler();
        LabelTreeNode rootNode = handler.getLabelTree();
        return loadLabelsRecursively(rootNode, selectedLabels);
    }

    private DefaultMutableLabelNode loadLabelsRecursively(LabelTreeNode obj, HashMap selectedLabels) {
        DefaultMutableLabelNode result = null;
        if (obj != null) {
            T_test_label label = (T_test_label) obj.getObject();
            if (label != null && selectedLabels != null &&
                    selectedLabels.containsKey(label.getId())) {
                obj.setSelected(true); // mark label selected
            }
            result = new DefaultMutableLabelNode(obj);
            TreeNode[] children = obj.getChildren();
            for (int i = 0; i < children.length; i++) {
                LabelTreeNode child = (LabelTreeNode) children[i];
                DefaultMutableLabelNode childNode = loadLabelsRecursively(child, selectedLabels);
                result.add(childNode);
            }
        }
        return result;
    }
}
